package string_question.leecode.test68;

import java.util.ArrayList;
import java.util.List;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/7/7 11:06
 */
public class Solution1 {

    public List<String> fullJustify(String[] words, int maxWidth) {
        List<String> ans = new ArrayList<>();   // 存储最后的结果
        int curSite = 0;
        int start = 0;
        int end = 0;
        for (int i = 0; i < words.length; ) {
            if ((curSite == 0 && curSite + words[i].length() <= maxWidth) || (curSite > 0 && (curSite + 1 + words[i].length()) <= maxWidth)) {
                if (curSite == 0) {
                    curSite = curSite + words[i].length();
                } else {
                    curSite = curSite + 1 + words[i].length();
                }
                end++;
                i++;
            } else {
                int size = end - start;
                // 首先计算出当前的空格数
                int spaceNum = maxWidth - curSite + (size - 1);
                if (size == 1) {
                    ans.add(words[start] + generateBlank(spaceNum));
                } else {
                    StringBuilder temp = new StringBuilder();
                    temp.append(words[start]);
                    int ever = spaceNum / (size - 1);
                    int more = spaceNum - ever * (size - 1);
                    String moreBlank = generateBlank(ever + 1);
                    int k = 1;
                    for (int j = 0; j < more; j++) {
                        temp.append(moreBlank + words[start + k++]);
                    }
                    String curBlank = generateBlank(ever);
                    for (int j = k; j < size; j++) {
                        temp.append(curBlank + words[start + j]);
                    }
                    ans.add(temp.toString());
                }
                // 更新start
                start = end;
                curSite = 0;
            }
        }
        // 单独计算最后一行
        StringBuilder temp = new StringBuilder();
        temp.append(words[start]);
        for (int j = start + 1; j < end; j++) {
            temp.append(" " + words[j]);
        }
        temp.append(generateBlank(maxWidth - curSite));
        ans.add(temp.toString());
        return ans;
    }

    private String generateBlank(int n) {
        StringBuilder ans = new StringBuilder();
        for (int i = 0; i < n; i++) {
            ans.append(" ");
        }
        return ans.toString();
    }

}
